package com.cnct.springbootthymeleaf.controller;

import com.cnct.springbootthymeleaf.entity.User;
import com.cnct.springbootthymeleaf.jpa.UserJPA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserJPA userJPA;

    static {
        System.out.println("123");
    }
    @RequestMapping("/list")
    public String  listUser(Model model) {
        List<User> userList = userJPA.findAll();
        model.addAttribute("users", userList);
        return "/user/list";
    }
    @RequestMapping("/delete")
    public String  deleteUser(Model model,String uid) {
        User user = new User();
        user.setId(Integer.parseInt(uid));
        userJPA.delete(user);
        return "redirect:/user/list";
    }

    @RequestMapping("/login")
    @ResponseBody
    public Map<String,Object> login(String username, String password, HttpSession session){
        Map<String,Object> map = new HashMap();
        User user = userJPA.findOne(username,password);
        if (user !=null){
            map.put("msg","登录成功");
            session.setAttribute("user",user);
        }else{
            map.put("msg","登录失败");
        }
        return map;
    }

    @RequestMapping("/loginSuccess")
    public String loginSuccess(){
        return "/user/loginSuccess";
    }

    @RequestMapping("/register")
    @ResponseBody
    public Map<String,Object> register(User user){
        Map<String,Object> message = new HashMap<>();
        user.setAge(18);
        User registerUser = userJPA.save(user);
        if (registerUser != null){
            message.put("msg","注册成功");
        }else {
            message.put("msg","注册失败");
        }
        return message;
    }
}